package vn.allmobile.ambnews.network;

import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.locks.ReentrantLock;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import vn.allmobile.ambnews.data.Article;
import vn.allmobile.ambnews.data.CacheFile;
import vn.allmobile.ambnews.data.Category;
import vn.allmobile.ambnews.data.DbFeedAdapter;
import vn.allmobile.ambnews.data.DbSchema;
import vn.allmobile.ambnews.data.ListPaperData;
import vn.allmobile.ambnews.data.ListProvinces;
import vn.allmobile.ambnews.data.Paper;
import vn.allmobile.ambnews.data.Weather;
import vn.allmobile.ambnews.network.HttpRequest.HttpRequestException;
import vn.allmobile.ambnews.utils.Contants;
import vn.allmobile.ambnews.utils.GlobalApplication;
import vn.allmobile.ambnews.utils.Log;
import vn.allmobile.ambnews.utils.PreferenceManager;
import vn.allmobile.ambnews.utils.Utils;

import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.text.TextUtils;

import com.aphidmobile.utils.IO;
import com.google.gson.Gson;
import com.nostra13.universalimageloader.core.ImageLoader;


public class LoaderThread extends Thread{

	private LoadDataListener _mloadDataListener;
	private volatile int loadMsg = -1;
	private boolean running = false;
public LoaderThread() {
		// TODO Auto-generated constructor stub
		setPriority(1);
		running = true;
	}

	
	

	public void setloadDataListener(LoadDataListener listener) {
		_mloadDataListener = listener;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Thread#run()
	 */
	@Override
	public void run() {
		while (true) {
			final int loadMsg = NetworkAPI.getSetRequest();			
			if (!this.running) {
				return;
			}
			try {
				Thread.sleep(100L);										
			
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
				
			
			if (loadMsg == -1)
			{					
				continue;					
			}
					
			loadData(loadMsg);																	
		}
	}


	private void loadData(int loadMsg) {
		Log.v("EXECUTE:" + loadMsg);
		switch (loadMsg) {
		case Contants.MSG_LOAD_PAPER:
			loadListPaper();
			break;
		case Contants.MSG_LOAD_CAT:
			loadListCategory();
			break;
		case Contants.MSG_LOAD_LIST:
			loadListArticle(NetworkAPI._currentPaperId, NetworkAPI._currentCategoryId , false);
			break;
		case Contants.MSG_LOAD_USERPAPER:
			Log.v("MSG_LOAD_USERPAPER");
			loadUserData();
			break;	
		default:
			break;
		}		
		
	}

	private static List<Article> getListArticleFromSv(String ppId,String catId, boolean isSync, long lastSync) 
	{
		
		ImageLoader.getInstance().pause();
long ct = System.currentTimeMillis();
Log.v("start loading:" + ct);
		System.setProperty("java.net.preferIPv4Stack" , "true");
		String url = "http://news.allmobile.vn/"
				+ ppId + "/"
				+ catId + "/list.html?ts="+lastSync;
		String response = "";
		
		try{
    		//System.setProperty("http.keepAlive", "false");    		
    		HttpRequest request = HttpRequest.get(url);
    		request.connectTimeout(5000);
    		request.readTimeout(5000);
    				//.accept("application/json");    
    		//request.getConnection().setReadTimeout(10000);
    		request.getConnection().setUseCaches(false);
    		request.getConnection().setRequestProperty ( "user-agent" ,  
                    "Mozilla/4.0 (compatible; 6.0 MSIE; Windows NT 5.1; SV1)" );
    		//request.getConnection().setRequestProperty("Content-Length", "1000");
        	//Tell server to gzip response and automatically uncompress
        	request.acceptGzipEncoding().uncompress(true);
        	response = request.body();
        	//Log.v(response);
        	
    	}catch(HttpRequestException e){
    		e.printStackTrace();
    		response =  null ;
    		ImageLoader.getInstance().resume();
    	}
		List<Article> listArticles = new ArrayList<Article>();
		
Log.v("finish loading :" + System.currentTimeMillis() + " colapsetime: " + (System.currentTimeMillis() - ct) );
ct =  System.currentTimeMillis();
Log.v("start processing:" + ct);

		if (response != null) {
			try {
				JSONArray jaList = new JSONArray(response);
				for (int i = 0; i < jaList.length(); i++) {
					JSONObject joList = jaList.getJSONObject(i);
					String id = joList.getString("id");
					String cat_id = joList.getString("cat_id");
					String paper_id = joList.getString("pp_id");
					String title = joList.getString("title");
					String description = joList.getString("description");
					String image = joList.getString("image");
					String pubdate = joList.getString("date");
					String image_width = joList.getString("img_width");
					String image_height = joList.getString("img_height");
					String content 	= joList.getString("content");
					String article_url 	= joList.getString("url");
					String slug 	= joList.getString("slug");
					Article article = new Article(id, title, description,
							pubdate, image, paper_id, cat_id);
					article.setHeight(image_height);
					article.setWidth(image_width);
					article.setContent(content);
					article.setUrl(article_url);
					article.setSlug(slug);
					if(isSync)
					{
						article.setType(DbSchema.ARTICLE_TYPE_SYNC);
					}
				
					listArticles.add(article);
				}
				
				
				if(listArticles.size() > 0 )
				{
					int i= 0  ;
					String cat_image = "";
					while(cat_image.isEmpty())
					{					
						cat_image = listArticles.get(i).getImage();
						i++;
					}
				try{
					for(Paper pp : NetworkAPI._papers )
					{
						if(ppId.equals(pp.getId()))
						{
							for(Category cat : pp.getCategories())
							{
								if(catId.equals(cat.getId()))
								{
									cat.setImage(listArticles.get(0).getImage());
								}
							}
						}
					}
					CacheFile.saveFile(GlobalApplication._(), Contants.CACHE_PAPER_NAME,
							Contants.CACHE_PATH, IO.convertObjectToString(new ListPaperData(
									NetworkAPI._papers)));
					
					for(Paper pp : NetworkAPI._userListPapers )
					{
						if(ppId.equals(pp.getId()))
						{
							for(Category cat : pp.getCategories())
							{
								if(catId.equals(cat.getId()))
								{
									cat.setImage(listArticles.get(0).getImage());
								}
							}
						}
					}
					CacheFile.saveFile(GlobalApplication._(), Contants.CACHE_PAPER_NAME,
							Contants.CACHE_ALLPAPERS_LIST, IO.convertObjectToString(new ListPaperData(
									NetworkAPI._userListPapers)));
				}catch(Exception e){
					e.printStackTrace();
				}
					
					
				}
				Log.v("finish processing :" + System.currentTimeMillis() + " colapsetime: " + (System.currentTimeMillis() - ct) );
				ImageLoader.getInstance().resume();
				return listArticles;
				//fileName
				

			} catch (JSONException e) {
				// TODO Auto-generated catch block
				//this._mloadDataListener.onListloadFail();
				e.printStackTrace();
			}

		}
	
	return listArticles;		
	}
	

	public  void loadListArticle(String ppId, String catId, boolean isSync) {
	
		Log.v("load article");
		
		List<Article> articles = new ArrayList<Article>();
		
		//articles= mDbFeedAdapter.getListArticle(ppId, catId);
		long lastSyncTime =   DbFeedAdapter.getLastSyncTime(ppId, catId);
		Log.v("lastSyncTime:" + lastSyncTime);
		int iCount = 0;
	 do{
		 if(lastSyncTime ==  0)
			{
				// lay moi tu server
				List<Article> articles_fromsv = getListArticleFromSv(ppId, catId,isSync,0);
				if(articles_fromsv.size() > 0)
				{
					//insert into database
					DbFeedAdapter.addListAticle(articles_fromsv);
					//update lastSync
					DbFeedAdapter.updateLastSync(ppId, catId);			
					articles = articles_fromsv;
				}			
			}
			else
			{
				if(((Utils.currentMillis() - lastSyncTime*1000L) >  NetworkAPI._syncTime *60*1000L )  && NetworkChangeReceiver.isConnected(true))
				{
					Log.v("last sync time not equal 0");
					List<Article> articles_fromsv = getListArticleFromSv(ppId, catId,isSync,lastSyncTime);
					if(articles_fromsv.size() > 0)
					{							
						DbFeedAdapter.addListAticle(articles_fromsv);
						DbFeedAdapter.updateLastSync(ppId, catId);
					}				
				}
				articles = DbFeedAdapter.getListArticle(ppId, catId,false);
				Log.v("articles in db:"+ articles.size());
			}
		 
		  if(articles.size() == 0)
		  {
			  lastSyncTime = 0;
			  iCount ++;
		  }
	 }while(articles.size() == 0 && iCount < 2);
		
	 	//DbFeedAdapter._(GlobalApplication._()).close();
	 	
		if(!isSync)
		{
			//if this is not sync task
			if(articles.size()>0)
			{
				NetworkAPI._listArticles = articles;
				this._mloadDataListener.onListloadSuccess();
			}
			else
			{
				// get new article
				this._mloadDataListener.onListloadFail();
			}
		}
		Log.v("load list done:" + catId);	
		
	}

	private void loadListCategory() {
		
		if(NetworkAPI._papers.get(NetworkAPI._currentPaperIndex).getCategories().size()>0)
		{
			this._mloadDataListener.onCategoryloadSuccess();
			return; 
		}
		
		String response = "";
		Log.v("http://news.allmobile.vn/" + NetworkAPI._currentPaperId
				+ "/list.html");
		response = RestClient._().connect("http://news.allmobile.vn/"
				+ NetworkAPI._currentPaperId + "/list.html");
		List<Category> listCategories = new ArrayList<Category>();
	
		if (response != null) {
			try {
				JSONArray jaList = new JSONArray(response);
				for (int i = 0; i < jaList.length(); i++) {
					JSONObject joList = jaList.getJSONObject(i);
					String id = joList.getString("id");
					String title = joList.getString("title");
					String image = joList.getString("image");
					Category category = new Category(id, title, image, "");
				
					listCategories.add(category);
				}
				NetworkAPI._papers.get(NetworkAPI._currentPaperIndex)
						.setCategories(listCategories);
				// NetworkAPI._listArticles = listArticles;
				Gson gson = new Gson();
				CacheFile.saveFile(GlobalApplication._(),
						Contants.CACHE_PAPER_NAME, Contants.CACHE_PATH,
						gson.toJson(NetworkAPI._papers));
				this._mloadDataListener.onCategoryloadSuccess();

			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
	}

	private void loadListPaper() {
		// TODO Auto-generated method stub
		int isUpdate = 0;
		String response = "";
		List<Paper> arrPapers = new ArrayList<Paper>();
		PackageInfo pInfo = null;
		try {
			pInfo = GlobalApplication._().getPackageManager().getPackageInfo(GlobalApplication._().getPackageName(), 0);
		} catch (NameNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		String version = pInfo.versionName;
		String response_update = RestClient._()
				.connect("http://news.allmobile.vn/checkupdate.html?appver="+version+"&ppver="+PreferenceManager.getPaperVersion());		
		try {
			JSONObject joUpdate =  new JSONObject(response_update);
			String paperVersion = joUpdate.getString("pp");
			NetworkAPI._appState	= joUpdate.getString("app");
			Log.v("paperVersion:" +paperVersion);
			Log.v("app state:" + NetworkAPI._appState);
			if(Integer.parseInt(paperVersion) != PreferenceManager.getPaperVersion())
			{
				NetworkAPI._isPaperUpdated = true;
				isUpdate = 1;
				PreferenceManager.setPaperVersion(Integer.parseInt(paperVersion));
			}
		} catch (JSONException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		response = CacheFile.readFile(GlobalApplication._(),
				Contants.CACHE_PAPER_NAME, Contants.CACHE_PATH);	
		int iCount = 0;
		do
		{	
			iCount++;
			 try{
				 if (isUpdate == 1 || response == null || TextUtils.isEmpty(response)) {
					 isUpdate = 0;
					Log.v("load paper from server");
					String response_fromsv = RestClient._()
							.connect("http://news.allmobile.vn/paper.html");
												
					if(response_fromsv != null)
					{							
						try {
							JSONArray jaPapers = new JSONArray(response_fromsv);
							
							for (int i = 0; i < jaPapers.length(); i++) {
								List<Category> Category = new ArrayList<Category>();
								JSONObject joPaper = jaPapers.getJSONObject(i);
								// JSONArray jaPaper = jaPapers.getJSONArray(i);
								String id = joPaper.getString("id");
								String title = joPaper.getString("title");
								String img = joPaper.getString("image");
								String slug = joPaper.getString("slug");
								String category = joPaper.getString("categories");
								
								if (category != null) {
									JSONArray jaarrCategory = new JSONArray(category);
									// Log.v(joarrCategory.keys().toString())
									for (int j = 0; j < jaarrCategory.length(); j++) {
										JSONObject joCategory = jaarrCategory.getJSONObject(j);
										String cat_id = joCategory.getString("id");
										String cat_title = joCategory.getString("title");
										String cat_img = joCategory.getString("image");
										Category cat = new Category(cat_id, cat_title, cat_img, "");
										Category.add(cat);
										
									}

								} else {
									Category.clear();
								}

								Paper paper = new Paper(id, title, img, Category);
								paper.setSlug(slug);
								paper.setEnable(false);
								// Log.v(paper.getTitle() + ":" + Category.size());

								arrPapers.add(paper);

								// arrPapers

							}

							if(arrPapers.size()>0)				
								CacheFile.saveFile(GlobalApplication._(), Contants.CACHE_PAPER_NAME,
									Contants.CACHE_PATH, IO.convertObjectToString(new ListPaperData(
											arrPapers)));													
							
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}							
				}
				else
				{					
					Log.v("load list paper from cache");
					ListPaperData list =  (ListPaperData) IO.convertStringToObject(response, ListPaperData.class);
					arrPapers = list.getListPaper();
					if(arrPapers.size() == 0 )
					{
						isUpdate = 1;
					}
				}			
			
			if(arrPapers.size() > 0)
			{
				NetworkAPI._papers = arrPapers;			
				if(PreferenceManager.isFirstTime())
				{
					PreferenceManager.setisFirstTime();
				}
				//loadHotNews();
				if(NetworkChangeReceiver.isConnected(true))
				{
					//loadLocation();
					//loadWeather(58);
				}
					
				/*if(NetworkAPI._fromNotification)
				{
					loadListArticle(NetworkAPI._currentPaperId, NetworkAPI._currentCategoryId , false);			
				}
				else
				{
					this._mloadDataListener.onPaperloadSuccess();
				}*/	
				paperToMap();
				this._mloadDataListener.onPaperloadSuccess();
				
			}
				
			}catch(Exception e){
				e.printStackTrace();
				Log.v("get Exception:"+ Contants.CACHE_PATH + Contants.CACHE_PAPER_NAME);
				CacheFile.deleteCache(GlobalApplication._(), Contants.CACHE_PATH + Contants.CACHE_PAPER_NAME);
				isUpdate = 1;
			}
			
		}while(isUpdate == 1|| iCount < 1);
				
	}
	
	
	public void paperToMap()
	{
		Map<String, Paper> papers = new TreeMap<String, Paper>();
		for(Paper pp : NetworkAPI._papers)
		{
			//Map<String, Paper> cat = new TreeMap<String, Paper>();		
			papers.put(pp.getId(),pp);			
		}
		NetworkAPI._papersMap = papers;
		
	}

	
	public void loadHotNews()
	{

		Log.v("http://news.allmobile.vn/hot.html");
		long lastestSync = 0L;
		List<Article> listArticles = new ArrayList<Article>();
		if(NetworkChangeReceiver.isConnected(true))
		{
			//Log.v("load hot from server");
			try{
				Article articleLatestHot = DbFeedAdapter.getLatestHotArticle();
				String latestSync = articleLatestHot.getPubdate();
			
				lastestSync =  Utils.datetime2timestamp(latestSync);			
	            //Log.v("hot news:" +  lastestSync);
			}catch(Exception e){
				
			}

			String response_fromsv = RestClient._().connect("http://news.allmobile.vn/hot.html?ts=" + lastestSync);
			
			if (response_fromsv != null) {				
				try {
					JSONArray jaList = new JSONArray(response_fromsv);
					for (int i = 0; i < jaList.length(); i++) {
						JSONObject joList = jaList.getJSONObject(i);
						String id = joList.getString("id");
						String cat_id = joList.getString("cat_id");
						String paper_id = joList.getString("pp_id");
						String title = joList.getString("title");
						String description = joList.getString("description");
						String image = joList.getString("image");
						String pubdate = joList.getString("date");
						String image_width = joList.getString("img_width");
						String image_height = joList.getString("img_height");
						String content 	= joList.getString("content");
						String article_url 	= joList.getString("url");
						String slug			= joList.getString("slug");
						Article article = new Article(id, title, description,
								pubdate, image, paper_id, cat_id);
						article.setHeight(image_height);
						article.setWidth(image_width);
						article.setContent(content);
						article.setUrl(article_url);
						article.setSlug(slug);
						article.setType(DbSchema.ARTICLE_TYPE_HOT); // hot article
					//	Log.v(article.getTitle());
						listArticles.add(article);		
						
						
					}
								

				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				//Log.v("listArticles size: " + listArticles.size());
				if(listArticles.size()>0)
				{
					DbFeedAdapter.addHotArticles(listArticles);				
				}
			}
		}
		
		
		listArticles = DbFeedAdapter.getListArticle(null, null, true);							
		NetworkAPI._listHotArticles = listArticles;			
		//Log.v(response);
		
		
	}
	
	public void loadLocation()
	{
		String response = RestClient._().connect("http://www.hoatieuonline.vn/service/thoitiet/json");
		if(response != null)
		{
			Gson gson = new Gson();					
			ListProvinces _provices = gson.fromJson(response, ListProvinces.class);
			NetworkAPI._provinces = _provices.get_provinces();
			
		}
	}
	
	public void loadWeather(int province)
	{
		String response = RestClient._().connect("http://www.hoatieuonline.vn/service/thoitiet/json-thoitiet/matinh/" + province);
		if(response != null)
		{
			try {
				JSONObject json = new JSONObject(response);
				json.getString("day");
				String description = json.getString("status");
				String image  = json.getString("image");
				String tmin = json.getString("t_min");
				String tmax = json.getString("t_max");							
				NetworkAPI._currentWeather = new Weather(province,tmin+" - " + tmax, image, description); 				
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		
	}
	
	
	public static void loadUserPaper()
	{
		Log.v("loadUserData");
		String mCachedFile = CacheFile.readFile(GlobalApplication._(),
				Contants.CACHE_ALLPAPERS_LIST, Contants.CACHE_PATH);
		if (mCachedFile == null) {// First load
			NetworkAPI._userListPapers = new ArrayList<Paper>();
		} else {
			ListPaperData list = (ListPaperData) IO.convertStringToObject(
					mCachedFile, ListPaperData.class);			
			NetworkAPI._userListPapers = list.getListPaper();	
			Log.v("load user data");			
			NetworkAPI._readySync =  true;					
		}
		
	}
	
	public  void loadUserData() {
		loadUserPaper();
		this._mloadDataListener.onUserloadSuccess();
		
	}

}
